cmake_minimum_required(VERSION 3.28)
# # 防止交叉编译时尝试生成主机可执行程序
set(CMAKE_TRY_COMPILE_TARGET_TYPE STATIC_LIBRARY)

project(Template)

# Find package ST_HAL
set(CMAKE_MODULE_PATH ${PROJECT_SOURCE_DIR}/system/st_hal)
find_package(ST_HAL)

# Find package FreeRTOS
set(CMAKE_MODULE_PATH ${PROJECT_SOURCE_DIR}/system/freertos)
find_package(FreeRTOS)

file(GLOB SRCS
    ${PROJECT_SOURCE_DIR}/app/*.cpp
    ${PROJECT_SOURCE_DIR}/driver/usart/*.cpp
    ${PROJECT_SOURCE_DIR}/driver/fatfs/*.c
    ${PROJECT_SOURCE_DIR}/driver/fatfs/*.cpp
    ${PROJECT_SOURCE_DIR}/app/TestTask/*.cpp
)
set_source_files_properties(${PROJECT_SOURCE_DIR}/driver/fatfs/*.c PROPERTIES LANGUAGE C)

include_directories(
    ${ST_HAL_INCLUDE_DIRS}
    ${FreeRTOS_INCLUDE_DIRS}
    ${PROJECT_SOURCE_DIR}/app
    ${PROJECT_SOURCE_DIR}/system
    ${PROJECT_SOURCE_DIR}/driver/usart
    ${PROJECT_SOURCE_DIR}/driver/fatfs
    ${PROJECT_SOURCE_DIR}/app/TestTask
)


set(STARTUP_FILE ${ST_HAL_STARTUP_FILE})
set(LINKER_SCRIPT ${ST_HAL_LINKER_SCRIPT})

set(LIBS_FLAG "-lc -lstdc++ -lnosys -lm")
set(C_DEFS "-DUSE_HAL_DRIVER -DSTM32F407xx")

enable_language(ASM)

set(CMAKE_C_COMPILER arm-none-eabi-gcc)
set(CMAKE_CXX_COMPILER arm-none-eabi-g++)
set(CMAKE_ASM_COMPILER arm-none-eabi-gcc)
set(CMAKE_OBJCOPY arm-none-eabi-objcopy)
set(CMAKE_SIZE arm-none-eabi-size)

set(MCU_FLAGS "-mcpu=cortex-m4 -mthumb -mfpu=fpv4-sp-d16 -mfloat-abi=hard")

set(CMAKE_ASM_FLAGS "-x assembler-with-cpp ${MCU_FLAGS} -g -O0 -Wall -fdata-sections -ffunction-sections -MMD")
set(CMAKE_C_FLAGS "${MCU_FLAGS} ${C_DEFS} -g -O1 -Wall -fdata-sections -ffunction-sections -MMD")
set(CMAKE_CXX_FLAGS "${MCU_FLAGS} ${C_DEFS} -g -O1 -Wall -fdata-sections -ffunction-sections -MMD")


set(CMAKE_EXE_LINKER_FLAGS "${MCU_FLAGS} -g -O0 -specs=nano.specs -specs=nosys.specs -T ${LINKER_SCRIPT} ${LIBS_FLAG} -Wl,-Map=${PROJECT_BINARY_DIR}/${PROJECT_NAME}.map,--cref -Wl,--gc-sections -Wl,-u_printf_float")

add_executable(${PROJECT_NAME}.elf ${STARTUP_FILE} ${ST_HAL_SRCS} ${FreeRTOS_SRCS} ${SRCS})

add_custom_command(TARGET "${PROJECT_NAME}.elf" POST_BUILD
COMMAND ${CMAKE_OBJCOPY} -Obinary ${PROJECT_BINARY_DIR}/${PROJECT_NAME}.elf ${PROJECT_BINARY_DIR}/${PROJECT_NAME}.bin
COMMAND ${CMAKE_OBJCOPY} -Oihex ${PROJECT_BINARY_DIR}/${PROJECT_NAME}.elf ${PROJECT_BINARY_DIR}/${PROJECT_NAME}.hex
COMMENT "Building binary file and hex file"
COMMAND ${CMAKE_COMMAND} -E copy ${PROJECT_BINARY_DIR}/${PROJECT_NAME}.bin "${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}.bin"
COMMAND ${CMAKE_COMMAND} -E copy ${PROJECT_BINARY_DIR}/${PROJECT_NAME}.hex "${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}.hex"
COMMAND ${CMAKE_SIZE} --format=berkeley ${PROJECT_NAME}.elf ${PROJECT_NAME}.hex
COMMENT "Invoking: Cross Arm GNU Print Size"
)






